'''Simple data loader module.

$Id: data.py 528 2009-01-18 07:46:39Z casey.duncan $
'''

import os
from model import obj
import pyglet

try:
	data_py = os.path.abspath(os.path.dirname(__file__))
	model_dir = os.path.normpath(os.path.join(data_py, '..', 'model'))
	texture_dir = os.path.normpath(os.path.join(data_py, '..', 'texture'))
	map_dir = os.path.normpath(os.path.join(data_py, '..', 'map'))
except:
	# py2exe
	model_dir = 'model'
	texture_dir = 'texture'

def filepath(filename):
	'''Determine the path to a file in the data directory.
	'''
	return os.path.join(data_dir, filename)

def load(filename, mode='rb'):
	'''Open a file in the data directory.

	"mode" is passed as the second arg to open().
	'''
	return open(os.path.join(data_dir, filename), mode)

def load_model(filename, compile_mesh=True):
	model = obj.OBJ(os.path.join(model_dir, filename))
	if compile:
		for mesh in model.mesh_list:
			mesh.compile()
	return model

_textures = {}

def texture(filename):
	global _textures
	if filename not in _textures:
		_textures[filename] = pyglet.image.load(
			os.path.join(texture_dir, filename)).get_mipmapped_texture()
	return _textures[filename]

def map_texture(filename):
	return pyglet.image.load(os.path.join(map_dir, filename)).texture
